<template>
  <div class="bg-gray">
    <b-container>
      <!--      main-->
      <b-row class="d-none d-lg-block">
        <b-col cols="12">
          <b-breadcrumb class="bg-gray bread-border mb-2">
            <b-breadcrumb-item to="/space">
              <b-icon icon="house-fill" scale="1.25" shift-v="1.25"/>
              个人空间
            </b-breadcrumb-item>
            <b-breadcrumb-item active>
              聊天列表
            </b-breadcrumb-item>
          </b-breadcrumb>
        </b-col>
      </b-row>
      <b-row class="">

        <b-col class="text-center m-0 p-0 my-2" v-for="(user,index) in users">
          <b-avatar
              size="60px" class="mx-2 mx-md-3"
              :variant="user.avatarcolor"
              :src="gensrc(user.avatarpath)"
              button
              @click="changeuser(user)"
          />
        </b-col>
      </b-row>
      <b-row class="mb-2">
        <b-col>
          <div class="my-card">
            <b-row class="m-0" v-if="curuser">
              <b-col cols="12" class="border-b">
                <h5 class="mt-1">{{curuser.nickname}}</h5>
              </b-col>
<!--              content-->
              <b-col cols="12" class="my-2  content border-bottom overflow-auto">
                <b-row v-for="(rec,index) in records" class="mb-2">
<!--                  left-->

                  <b-col cols="auto" v-if="rec.fromid === curuser.uuid" class="">

                    <b-avatar size="40px"
                              :variant="curuser.avatarcolor"
                              :src="gensrc(curuser.avatarpath)"
                    ></b-avatar>
                  </b-col>
                  <b-col cols="8" md="6"  v-if="rec.fromid === curuser.uuid" class="text-left px-0 ">
                      <span class="recorditem-left p-2 d-block">{{rec.content}}</span>
                  </b-col>
                  <b-col cols="12" v-if="rec.fromid === curuser.uuid" >
                    <span class="small-text color-light-gray d-block mt-2">{{formattime(rec.sendtime)}}</span>
                  </b-col>

<!--                right-->

                  <b-col cols="8" md="6" v-if="rec.fromid !== curuser.uuid" class="text-right px-0 ml-auto">
                    <p class="recorditem-right p-2 mb-0">{{rec.content}}</p>
                  </b-col>
                  <b-col cols="auto" v-if="rec.fromid !== curuser.uuid" class="">

                    <b-avatar size="40px"
                              :variant="$store.state.avatarcolor"
                              :src="gensrc($store.state.avatarpath)"
                    ></b-avatar>
                  </b-col>
                  <b-col cols="12" v-if="rec.fromid !== curuser.uuid"  class="text-right">
                    <span class="small-text color-sub-theme  mt-2" v-if="rec.status ==1">已读</span>
                    <span class="small-text color-theme  mt-2" v-else>未读</span>
                    <span class="small-text color-light-gray  mt-2">
                      {{formattime(rec.sendtime)}}
                    </span>
                  </b-col>

                </b-row>


              </b-col>
              <b-col cols="" class="mb-2">
                <b-input v-model="content" @keypress.enter="sendmsg"></b-input>
              </b-col>
              <b-col cols="auto" class="text-center pl-0 mb-2">
                <b-button variant="primary" @click="sendmsg">发送</b-button>
              </b-col>
            </b-row>
            <b-row class="m-0 mt-2" v-else>
                <b-col cols="12" class="text-center">
                  <h4 class="text-center">还没有聊天记录</h4>
                </b-col>

            </b-row>
          </div>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script>
  import urlconfig from "../urlconfig";

  export default {
    name: "Chat",
    data() {
      return {
        users: [],
        curuser: null,
        records: [],
        websock: null,
        content: '',
      }
    },
    computed: {},
    methods: {
      formattime(sendtime) {
        let date = new Date(sendtime)
        let month = date.getMonth() + 1
        let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        let min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        let sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return month + '月' + day + '日' + hour + ':' + min + ':' + sec
      },
      gensrc(path) {
        return urlconfig.baseUrl + urlconfig.avatarResource + path
      },
      makeToast(msg, res = true) {
        this.$bvToast.toast(msg, {
          title: res ? '操作成功!' : '操作失败！',
          variant: res ? 'primary' : 'danger',
          solid: true,
          autoHideDelay: 5000,
        })
      },
      init() {

        this.websock = new WebSocket(urlconfig.wsUrl);
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen: function () {
        console.log("WebSocket连接成功");
        //init


        if (this.$route.params.uuid) {
          let data = {
            type: 'pullOneUser',
            from: this.$store.state.uuid,
            to: this.$route.params.uuid,
            token: this.$store.state.token
          }
          this.websock.send(JSON.stringify(data))
        } else {
          let data = {
            type: 'pullAllUser',
            from: this.$store.state.uuid,
            token: this.$store.state.token
          }
          this.websock.send(JSON.stringify(data))
        }
      },
      websocketonerror: function (e) {
        this.makeToast('连接错误！', false)
        console.log("WebSocket连接发生错误");
      },
      websocketonmessage: function (e) {
        this.handleMsg(JSON.parse(e.data))
      },
      websocketclose: function (e) {
        console.log("connection closed (" + e.code + ")");
      },
      sendmsg() {
        let data = {
          type: 'chat',
          from: this.$store.state.uuid,
          token: this.$store.state.token,
          to: this.curuser.uuid,
          content: this.$ajax.encode(this.content)
        }
        this.websock.send(JSON.stringify(data))
        this.content = ''
      },
      handleMsg(data) {
        switch (data.msg) {
          case "pullAllUser":
            this.users = data.data
            break
          case "pullOneUser":
            this.changeuser(data.data,true)
            break
          case "subscribe":
            this.records = data.data.reverse()
            break
          case "chat":
            this.records.splice(this.records.length, 0, data.data)
            break
        }
      },
      saybye() {
        let data = {
          type: 'bye',
          from: this.$store.state.uuid,
          token: this.$store.state.token
        }
        this.websock.send(JSON.stringify(data))
      },
      changeuser(user, add = false) {
        this.curuser = user
        if (add) {
          this.users.splice(this.users.length, 0, user)
        }
        let data = {
          type: 'subscribe',
          from: this.$store.state.uuid,
          to: user.uuid,
          token: this.$store.state.token
        }
        this.websock.send(JSON.stringify(data))
      }

    },
    mounted() {
      this.init()
    },
    beforeDestroy() {
      this.saybye()
      this.websock.close()
    }
  }
</script>

<style scoped>
  .my-card {
    background: #ffffff;
    border-radius: 5px;
    box-shadow: #6e6e6e 1px 1px 5px;
  }

  .text-overflow {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .border-b {
    border-bottom: #b8b8b8 solid 1px;
  }

  .content {
    height: 500px;
  }
  .recorditem-left{
    background: #ef7b3e;
    color: white;
    border-radius: 5px;
  }

  .recorditem-right{
    background: #54c0cc;
    color: white;
    border-radius: 5px;

  }

</style>